package _interview75;

/**
 * 162. 寻找峰值
 */
public class No162 {
    /**
     * 0. 自由写法
     */
    public int findPeakElement(int[] nums) {
        int n = nums.length;
        int left = 0, right = n - 1;
        while (left <= right) {
            int mid = left + (right - left >> 1);
            if ((mid > 0 && nums[mid] > nums[mid - 1]) ||
                    (mid < n - 1 && nums[mid] < nums[mid + 1])) {
                left = mid + 1;
            } else right = mid - 1;
        }
        return right == -1 ? 0 : right;
    }

    /**
     * 1. 闭区间
     */
    public int findPeakElement1(int[] nums) {
        int left = 0, right = nums.length - 2;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] < nums[mid + 1]) left = mid + 1;
            else right = mid - 1;
        }
        return left;
    }

    /**
     * 2. 左闭右开
     */
    public int findPeakElement2(int[] nums) {
        int left = 0, right = nums.length - 1;
        while (left < right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] < nums[mid + 1]) left = mid + 1;
            else right = mid;
        }
        return left;
    }

    /**
     * 3. 开区间
     */
    public int findPeakElement3(int[] nums) {
        int left = -1, right = nums.length - 1;
        while (left + 1 < right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] < nums[mid + 1]) left = mid;
            else right = mid;
        }
        return right;
    }
}
